package ru.electron.menu.fragments;


import android.database.Cursor;
import android.net.Uri;
import android.provider.BaseColumns;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import ru.electron.menu.R;
import ru.electron.menu.activities.DishListActivity;
import ru.electron.menu.provider.MenuProvider;

public class DishListFragment extends AbstractListFragment {


    protected Cursor cursor;

    @Override
    public String getHeader() {
        int tagID = getActivity().getIntent().getIntExtra(DishListActivity.KEY_TAG, -1);
        Cursor tagCursor = getActivity().managedQuery(Uri.withAppendedPath(MenuProvider.URI_TAGS, tagID + ""), null, null, null, null);
        tagCursor.moveToFirst();
        return tagCursor.getString(tagCursor.getColumnIndex(MenuProvider.KEY_TAG_NAME));
    }

    @Override
    public ListAdapter getListAdapter() {
        int tagID = getActivity().getIntent().getIntExtra(DishListActivity.KEY_TAG, -1);
        cursor = getActivity().managedQuery(Uri.withAppendedPath(MenuProvider.URI_AVAILABLE_DISHES, tagID + ""), null, null, null, null);
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(getActivity(), R.layout.list_item, cursor, new String[]{MenuProvider.KEY_DISH_NAME, MenuProvider.KEY_PRICE}, new int[]{R.id.name, R.id.price}, 0);
        return adapter;
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        cursor.moveToPosition(position);
        int newDishId = cursor.getInt(cursor.getColumnIndex(BaseColumns._ID));
        DishDetailsFragment details = (DishDetailsFragment) getFragmentManager().findFragmentById(R.id.details_fragment);
        getListView().setItemChecked(position, true);

        details = DishDetailsFragment.newInstance(newDishId, cursor.getColumnIndex(MenuProvider.KEY_COUNT) == -1);

        FragmentTransaction ft = getFragmentManager().beginTransaction();

        ft.replace(R.id.details_fragment, details);
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        ft.commit();


    }
}
